import React, { useRef, useEffect, useState } from 'react';
import styles from './index.module.less';
import { Button, Popup, CheckList } from 'antd-mobile';
enum WidgetType {
  checkbox = 'checkbox',
  checkboxes = 'checkboxes',
  radio = 'radio',
  select = 'select',
  multiSelect = 'multiSelect',
}
const WidgetSelection = (props) => {
 
  const {
    onChange,
    value:propsValue,
    schema: { widget, title, enumList = [] }
  } = props;
  
  const [visiblePopus, setVisiblePopus] = useState(false);
  const [value, setValue] = useState(propsValue);
  const [map, setMap] = useState<Map<string,string>>(new Map());
  
  useEffect(() => {
    if (enumList) {
      const map = new Map();
      for (const item of enumList) {
        map.set(item.value, item.label);
      }
      setMap(map);
    }

  }, [enumList]);

  const handleChange = (val) => {

    setValue(val);
  };

  const onConfirm = () => {
    setVisiblePopus(false);
    console.log(value);
    
    onChange && onChange(value);
  };
 


 
  const renderCheckList = () => {

    return (
      <CheckList
        multiple={widget == WidgetType.checkbox || widget == WidgetType.checkboxes || widget ==WidgetType.multiSelect}
        value={value}
        onChange={handleChange}
      >
        {enumList.map((item: any) => (
          <CheckList.Item key={item.value} value={item.value}>
            {item.label}
          </CheckList.Item>
        ))}
      </CheckList>
    );
  };

  const renderDisplayValue = () => {
    let displayValue = [];
    if (Array.isArray(value)) {
      displayValue = value;
    } else {
      return <span className={styles.placeholder}>请选择</span>;
    }
    displayValue = displayValue.map((item) => {
      return map.get(item);
    });
    return displayValue.join(',');
  };

  return (
    <div className={styles.selectionWarp}>
      <div
        className={styles.trigger}
        onClick={() => {
          setVisiblePopus(true);
        }}
      >
        {renderDisplayValue()}
      </div>
      <Popup
        visible={visiblePopus}
        className={styles.selectionPopupWarp}
        onMaskClick={() => {
          setVisiblePopus(false);
        }}
        bodyStyle={{ height: '100vh' }}
      >
        <div className={styles.title}>
          <div
            onClick={() => {
              setVisiblePopus(false);
            }}
          >
            取消
          </div>
          <div className={styles.name}>{title}</div>
          <div
            className={styles.confirm}
            onClick={onConfirm}
          >
            确认
          </div>
        </div>
        {renderCheckList()}
      </Popup>
    </div>
  );
};

export default WidgetSelection;
